import React, { useRef } from 'react'
import { useState, useCallback, useEffect, useLayoutEffect } from './useHooks'
import worker_script from './demo_workers'

let w

const HooksDemo = () => {
	const [num, setNum] = useState(0)
	const [name, setName] = useState('amin')
	const [str, setStr] = useState('amin')
	const [str2, setStr2] = useState('amin')
	const [target, setTarget] = useState('')

	const addNum = useCallback(() => {
		setNum((n) => n + 1)
	}, [num])

	const changeName = () => {
		setName(name === 'amin' ? 'zf' : 'amin')
	}

	useEffect(() => {
		setStr(name + num + 1)
	})

	useLayoutEffect(() => {
		setStr2(name + num)
	}, [num, name])

	const startWorker = () => {
		if (typeof Worker !== 'undefined') {
			if (typeof w == 'undefined') {
				w = new Worker(worker_script)
			}
			w.onmessage = function (event) {
				setTarget(event.data)
				w.terminate()
				w = undefined
			}
		} else {
			setTarget('抱歉，你的浏览器不支持 Web Workers...')
		}
	}

	const send = () => {
		w &&
			w.postMessage({
				value: '你好啊',
				start: new Date(),
			})
	}

	const send2 = () => {
		const start = new Date()
		const array = new Array(20000000).fill(1)
		const arr = array.map((item, index) => {
			return index + 1
		})
		const end = new Date()
		setTarget(`hello world 你好啊 ${end - start}`)
	}

	const stopWorker = () => {
		w && w.terminate()
		w = undefined
	}

	return (
		<div>
			<button onClick={addNum}>add</button>
			<button onClick={changeName}>add2</button>
			<div>
				{num}
				<br />
				{name}
				<br />
				{str}
				<br />
				{str2}
			</div>
			<button onClick={startWorker}>开始</button>
			<button onClick={stopWorker}>停止</button>
			<button onClick={send}>发送</button>
			<button onClick={send2}>发送2</button>
			{target && <div>{target}</div>}
		</div>
	)
}

export default HooksDemo
